<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->

    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="14">
          <!-- 搜索框 -->
          <div>
            <el-input placeholder="请输入内容" v-model="userInfo.query" clearable @clear="getUserInfo">
              <el-button slot="append" icon="el-icon-search" @click="getUserInfo"></el-button>
            </el-input>
          </div>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addUser">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 绘制用户信息表格 -->

      <el-table :data="userInfoData" style="width: 100%" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column prop="username" label="用户姓名" width="180" align="center"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="180" align="center"></el-table-column>
        <el-table-column prop="mobile" label="电话" width="180" align="center"></el-table-column>
        <el-table-column prop="role_name" label="用户角色" width="180" align="center"></el-table-column>
        <el-table-column label="状态" width="180" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="userChange(scope.row)"
            ></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="eidtUserInfo(scope.row.id)"
            >修改</el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserinfo(scope.row.id)"
            >删除</el-button>
            <el-button type="warning" icon="el-icon-setting" size="mini" @click="settingRight(scope.row)">设置</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页功能 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="userInfo.pagenum"
        :page-sizes="[1, 2, 3, 5]"
        :page-size="userInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      ></el-pagination>

      <!-- 添加用户 -->

      <el-dialog
        title="添加用户"
        :visible.sync="addUserdialogVisible"
        width="50%"
        @close="addDialogClose"
      >
        <!-- 添加用户的表单，用户的具体信息 -->
        <el-form
          ref="addUserFormRef"
          :model="addUserForm"
          :rules="addUserFormRules"
          label-width="80px"
        >
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addUserForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addUserForm.password"></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addUserForm.email"></el-input>
          </el-form-item>
          <el-form-item label="电话" prop="mobile">
            <el-input v-model="addUserForm.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer">
          <el-button @click="addUserdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserData">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 修改用户信息 -->
      <el-dialog
        title="修改用户信息"
        :visible.sync="editUserdialogVisible"
        width="50%"
        @close="editUserClose"
      >
        <!-- 修改用户信息表单 -->
        <el-form
          ref="editUserformRef"
          :model="editUserform"
          :rules="editUserformRules"
          label-width="80px"
        >
          <el-form-item label="姓名:" prop="username">
            <el-input v-model="editUserform.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱:" prop="email">
            <el-input v-model="editUserform.email"></el-input>
          </el-form-item>
          <el-form-item label="电话:" prop="mobile">
            <el-input v-model="editUserform.mobile"></el-input>
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="editUserdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUserInfo">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 分配角色 -->
      <el-dialog title="角色分配" :visible.sync="settingRightdialogVisible" width="50%" @close="settingRightClose">
        <!-- 基本信息加载 -->
        <div>
          <p>当前的用户是:{{userinfo.username}}</p>
          <p>当前的角色是:{{userinfo.role_name}}</p>
          <p>分配的权限是:
            <!-- 下拉选择框 -->
              <el-select v-model="selectedroled" placeholder="请选择">
    <el-option
      v-for="item in rolesList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>


          </p>
        </div>


        <span slot="footer" class="dialog-footer">
          <el-button @click="settingRightdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="settingRightok">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
           
<script>
export default {
  data() {
    // 自定义校验规则
    var checkemail = (rule, value, cb) => {
      // 验证邮箱的正则
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        return cb();
      }
      cb(new Error('请提供正确的邮箱'));
    };
    var checkmobile = (rule, value, cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        return cb();
      }
      cb(new Error('请提供正确的手机号'));
    };
    return {
      // 用户信息
      userInfo: {
        query: '',
        pagenum: 1,
        pagesize: 2
      },
      // 总页码
      total: 0,
      // 用户信息
      userInfoData: [],
      // 控制添加用户的对话框显示和隐藏
      addUserdialogVisible: false,
      // 添加用户的具体信息
      addUserForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      // 添加用户校验规则
      addUserFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '用户名长度在 3 到 15 个字符',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          {
            min: 6,
            max: 15,
            message: '密码长度在 6 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 修改用户信息弹窗
      editUserdialogVisible: false,
      editUserform: {
        username: '',
        email: '',
        mobile: ''
      },
      id: '', // 点击编辑时候获取的对应的用户的id 方便点击用户提交
      editUserformRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '用户名长度在 3 到 15 个字符',
            trigger: 'blur'
          }
        ],
        email: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkemail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { validator: checkmobile, trigger: 'blur' }
        ]
      },
      // 权限分配
      settingRightdialogVisible:false,
      // 用户信息
      userinfo:{},
      // 获取所有的角色信息
      rolesList:[],
      selectedroled:''
    };
  },
  methods: {
    async getUserInfo() {
      let { data: res } = await this.axios.get('users', {
        params: this.userInfo
      });
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('用户数据请求出错，请重试！');
      } else {
        this.userInfo.pagenum = res.data.pagenum;
        this.total = res.data.total;
        this.userInfoData = res.data.users;
        // console.log(this.userInfoData);
      }
    },
    // switch开关的修改
    async userChange(value) {
      // console.log(value.mg_state); // 获取到的是修改后的最新的值
      // 向后台发起请求
      let { data: res } = await this.axios.put(
        `users/${value.id}/state/${value.mg_state}`
      );
      // console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('请求发送错误');
        value.mg_state = !this.value.mg_state;
      }
      this.$message.success('更新用户状态成功');
    },
    handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.userInfo.pagesize = val;
      this.getUserInfo();
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.userInfo.pagenum = val;
      this.getUserInfo();
    },
    // 添加用户
    addUser() {
      this.addUserdialogVisible = true;
    },
    // 添加用户弹窗关闭事件，需要清空表单
    addDialogClose() {
      // 关闭弹窗，清空整个表单内容
      this.$refs.addUserFormRef.resetFields();
    },
    // 点击添加用户确定事件
    addUserData() {
      // 1.对用户输入的数据进行校验
      this.$refs.addUserFormRef.validate(async valid => {
        if (!valid) {
          this.$message.error('请确认信息填写是否正确，谢谢！');
        }
        // 接下来发起添加用户的请求
        let { data: res } = await this.axios.post('users', {
          ...this.addUserForm
        });
        //  console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败');
        }
        this.$message.success('添加用户成功');
        this.getUserInfo();
      });
      this.addUserdialogVisible = false;
    },
    async eidtUserInfo(id) {
      // 发起后台请求，获取数据
      // console.log(id);
      this.id = id;
      let { data: res } = await this.axios.get('users/' + id);
      // console.log(res);
      this.editUserform = res.data;

      this.editUserdialogVisible = true;
    },
    editUserInfo() {
      // 提交数据到后台
      // 提交前对数据进行校验
      this.$refs.editUserformRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请确认修改用户信息是否正确，谢谢！');
        }
        let { data: res } = await this.axios.put('users/' + this.id, {
          email: this.editUserform.email,
          mobile: this.editUserform.mobile
        });
        //  console.log(res);
        if (res.meta.status !== 200) {
          return this.$message.error('更新用户信息失败');
        }
        this.$message.success('更新用户信息成功');
        this.getUserInfo();

        this.editUserdialogVisible = false;
      });
    },
    editUserClose() {
      this.$refs.editUserformRef.resetFields();
    },
    // 删除用户信息
    async removeUserinfo(id) {
      // console.log(id);
      let result = await this.$confirm(
        '此操作将永久删除该文件, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err);
      // console.log(result);
      if (result !== 'confirm') {
        return this.$message.error('已经取消删除操作');
      }
      // 发起删除操作
      let { data: res } = await this.axios.delete('users/' + id);
      console.log(res);
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败');
      }
      this.$message.success('删除成功');
      this.getUserInfo();
    },
    async settingRight(userinfo){
      // 点击后需要获取对应的用户的信息
      this.userinfo=userinfo
      // 获取所有的角色信息
      let {data:res}=await this.axios.get('roles')
      console.log(res);
      if(res.meta.status!==200) {
        return this.$message.error('请求出错')
      }
      this.rolesList=res.data
      
      this.settingRightdialogVisible=true;
    },
    // 关闭分配权限弹窗，需要清空数据
    settingRightClose(){
      this.rolesList=[]
      this.selectedroled=''
    },
    async settingRightok(){
      // 点击确认按钮，需要提交对应的数据
      // console.log(this.selectedroled);
     let {data:res}=await this.axios.put(`users/${this.userinfo.id}/role`,{
        rid:this.selectedroled
      })
      if(res.meta.status!==200) {
        return this.$message.error('请求出错')
      }
      this.$message.success('角色分配成功')
      this.getUserInfo();
      // console.log(res);
      
      
      this.settingRightdialogVisible = false
    }
  },
  mounted() {
    this.getUserInfo();
  }
};
</script>
<style scoped lang="less">
.el-card {
  margin-top: 15px;
}
.el-table {
  margin-top: 20px;
}
.el-pagination {
  margin-top: 10px;
}
</style>